<template>
  <Modal
    v-model:active="WasherModalVueActive"
    transfer
    title="垫圈网格"
    :width="640"
    no-footer
    hide-mask
    draggable
    :mask-close="false"
  >
    <NativeScroll use-y-bar height="100%">
      <!-- <Divider text-position="left">选择器</Divider> -->
      <div class="title">
        <div class="title_color"></div>
        <div class="title_content">选择器</div>
      </div>
        <div class="chose-box">
          <RadioGroup vertical v-model:value="activeSelector" @change="onChangeSelector">
            <Radio v-for="(item, index) in selectorList" :key="item.label" :label="item.label">
              <div class="radio_box">
                <div class="radio_item">{{ item.content }}</div>
                <div class="selector-buttons">
                  <span class="selector-button" :class="{active: item.label === activeSelector }">
                    {{item.label ? '边' : '面'}}
                  </span>
                  <button class="icon-button" @click="handleClear(item.label)">
                    <img
                      src="../../assets/delete.svg"
                      alt=""
                      class="icon imgStyle"
                    />
                  </button>
                </div>
              </div>
            </Radio>
          </RadioGroup>
        </div>
      <Tabs v-model:active="activeTab">
        <TabPanel
          label="washer"
          name="垫圈参数"
          style="padding-top: 16px"
        >
          <Form
            inline
            :model="formWasher"
            :label-width="60"
            :label-suffix="'：'"
            align="middle"
          >
            <FormItem label="层数" style="margin-bottom: 16px">
              <NumberInput
                v-model:value="formWasher.numOfLayers"
                :disabled="formWasher.type === 'Rule'"
                @change="(val) => handleDataChange(formWasher.type, val)"
              />
            </FormItem>
            <FormItem label="类型" style="margin-bottom: 16px">
              <Select
                v-model:value="formWasher.type"
                :options="types"
                @change="(val: string) => handleDataChange(val, formWasher.numOfLayers)"
              ></Select>
            </FormItem>
            <FormItem label="" style="margin-bottom: 16px">
              <Checkbox v-model:checked="formWasher.boundaryLayer"
                >边界层</Checkbox
              >
            </FormItem>
          </Form>
          <div v-if="formWasher.type === 'Rule'">
            <div class="mb-10">
              <Table
                ref="tableWasherRule"
                use-y-bar
                use-x-bar
                :data="washerRuleData"
                border
                size="small"
                :height="400"
              >
                <TableColumn type="order" :width="40" />
                <TableColumn name="Min Diameter" id-key="minValue">
                  <template #default="{ row }">
                    <NumberInput v-model:value="row.minValue" />
                  </template>
                </TableColumn>
                <TableColumn
                  name="Symbol"
                  id-key="id"
                  :width="60"
                  text-align="center"
                >
                  <template #default="{ row }">
                    <span v-if="washerRuleSymbolType === 1">≤ D <</span>
                    <span v-else>< D ≤</span>
                  </template>
                </TableColumn>
                <TableColumn name="Max Diameter" id-key="maxValue">
                  <template #default="{ row }">
                    <NumberInput v-model:value="row.maxValue" />
                  </template>
                </TableColumn>
                <TableColumn name="Num Of Layers" id-key="numOfLayer">
                  <template #default="{ row }">
                    <NumberInput v-model:value="row.numOfLayer" />
                  </template>
                </TableColumn>
                <TableColumn name="方法" id-key="type">
                  <template #default="{ row }">
                    <Select
                      v-model:value="row.type"
                      :options="options"
                      transfer
                    />
                  </template>
                </TableColumn>
                <TableColumn name="值" id-key="value">
                  <template #default="{ row }">
                    <NumberInput v-model:value="row.value" />
                  </template>
                </TableColumn>
              </Table>
            </div>
            <div class="btn-wrap mb-20">
              <Button size="small" @click="addWasherRule">+</Button>
              <Button
                size="small"
                @click="delWasherRule"
                :disabled="washerRuleData.length <= 1"
                >-</Button
              >
            </div>
          </div>
          <Row v-else>
            <Column :span="18" :offset="3" class="mb-20">
              <Table
                ref="tableWasher"
                use-y-bar
                :data="data"
                border
                size="small"
                :height="400"
                :min-height="120"
              >
                <TableColumn type="order" :width="40" />
                <TableColumn name="方法" id-key="type">
                  <template #default="{ row }">
                    <Select
                      v-model:value="row.type"
                      :options="options"
                      transfer
                    />
                  </template>
                </TableColumn>
                <TableColumn name="值" id-key="value">
                  <template #default="{ row }">
                    <NumberInput v-model:value="row.value" />
                  </template>
                </TableColumn>
              </Table>
            </Column>
          </Row>
          <div class="footer">
            <Space>
              <Button @click="onClear">Clear</Button>
              <Button type="primary" @click="onSetWashers">Set Washers</Button>
            </Space>
          </div>
        </TabPanel>
        <TabPanel label="findpinhole" name="搜索孔" style="padding-top: 16px">
          <Form inline :model="formSearch" :label-width="100">
            <FormItem label="Min Diameter">
              <NumberInput v-model:value="formSearch.minDiameter" />
            </FormItem>
            <FormItem label="Max Diameter">
              <NumberInput v-model:value="formSearch.maxDiameter" />
            </FormItem>
          </Form>
          <div class="footer">
            <Button @click="onSearch">Auto Search</Button>
          </div>
        </TabPanel>
        <TabPanel label="hole" name="孔周网格规则" style="padding-top: 16px">
          <div class="mb-10">
            <Table
              ref="tableRule"
              use-y-bar
              use-x-bar
              :data="ruleData"
              border
              size="small"
              :height="400"
            >
              <TableColumn type="order" :width="40" />
              <TableColumn name="Min Diameter" id-key="minValue">
                <template #default="{ row }">
                  <NumberInput v-model:value="row.minValue" />
                </template>
              </TableColumn>
              <TableColumn
                name="Symbol"
                id-key="id"
                :width="60"
                text-align="center"
              >
                <template #default="{ row }">
                  <span v-if="ruleSymbolType === 1">≤ D <</span>
                  <span v-else>< D ≤</span>
                </template>
              </TableColumn>
              <TableColumn name="Max Diameter" id-key="maxValue">
                <template #default="{ row }">
                  <NumberInput v-model:value="row.maxValue" />
                </template>
              </TableColumn>
              <TableColumn name="Size Type" id-key="type">
                <template #default="{ row }">
                  <Select
                    v-model:value="row.type"
                    :options="ruleOptions"
                    transfer
                  />
                </template>
              </TableColumn>
              <TableColumn name="值" id-key="value">
                <template #default="{ row }">
                  <NumberInput v-model:value="row.value" />
                </template>
              </TableColumn>
            </Table>
          </div>
          <div class="btn-wrap mb-20">
            <Button size="small" @click="addHoleRule">+</Button>
            <Button
              size="small"
              @click="delHoleRule"
              :disabled="ruleData.length <= 1"
              >-</Button
            >
          </div>
          <div class="footer">
            <Space>
              <Button>Clear</Button>
              <Button type="primary" @click="onSetHoles">Set Holes</Button>
            </Space>
          </div>
        </TabPanel>
      </Tabs>
    </NativeScroll>
  </Modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import {
  Modal,
  Select,
  Divider,
  Form,
  FormItem,
  NumberInput,
  Checkbox,
  NativeScroll,
  Button,
  Tabs,
  TabPanel,
  Table,
  Space,
  RadioGroup,
  Radio,
  TableColumn,
  Row,
  Column,
  Notice,
} from "cax-ui";
import type { TableExposed } from "vexip-ui";
import { storeToRefs } from "pinia";
import { useCoreStore, _global } from "@/UI/store";
import { WasherCreateOptions } from "@/FrontProcessing/interface";
import { STATUS_CODE } from "@/FrontProcessing";
const coreStore = useCoreStore();

let { WasherModalVueActive } = storeToRefs(coreStore);

const activeTab = ref("washer");
const activeSelector = ref(0);
const selectorList = [{content: 'Surfaces includeing washers', label: 0}, {content: 'Curves with washers attached', label: 3}]

const types = [
  { label: "一致的", value: "Uniform" },
  { label: "变化的", value: "Varying" },
  { label: "Rule", value: "Rule" },
];

const formWasher = reactive({
  numOfLayers: 1,
  type: "Uniform",
  metaData: {
    maxValues: [],
    minValues: [],
    numOfLayers: [],
  },
  boundaryLayer: false, // 边界层
});
const formSearch = reactive({
  minDiameter: 4.0,
  maxDiameter: 12.0,
});
const options = [
  { label: "Width", value: "Width" },
  { label: "Scale", value: "Scale" },
];
const ruleOptions = [
  { label: "Number", value: "Number" },
  { label: "Size", value: "Size" },
];

const data = ref([
  {
    id: "0",
    type: "Width",
    value: 1,
  },
]);
const tableWasher = ref<TableExposed>();
const tableWasherRule = ref<TableExposed>();
const tableRule = ref<TableExposed>();
const washerRuleSymbolType = ref(0);
const washerRuleData = ref([
  { id: "0", minValue: 4, maxValue: 6, numOfLayer: 1, type: "Width", value: 1 },
  { id: "1", minValue: 6, maxValue: 8, numOfLayer: 1, type: "Width", value: 1 },
  {
    id: "2",
    minValue: 8,
    maxValue: 12,
    numOfLayer: 1,
    type: "Width",
    value: 1,
  },
]);
const ruleSymbolType = ref<0 | 1>(0);
const ruleData = ref([
  { id: "0", minValue: 4, maxValue: 6, type: "Number", value: 1 },
  { id: "1", minValue: 6, maxValue: 8, type: "Number", value: 1 },
  { id: "2", minValue: 8, maxValue: 12, type: "Number", value: 1 },
]);

function addHoleRule() {
  const len = ruleData.value.length;
  ruleData.value = [
    ...ruleData.value,
    {
      id: `${len}`,
      minValue: ruleData.value[len - 1].maxValue,
      maxValue: 0,
      type: "Number",
      value: 0,
    },
  ];
}

function delHoleRule() {
  const end = ruleData.value.length - 1;
  ruleData.value = ruleData.value.slice(0, end);
}

function addWasherRule() {
  const len = washerRuleData.value.length;
  washerRuleData.value = [
    ...washerRuleData.value,
    {
      id: `${len}`,
      minValue: washerRuleData.value[len - 1].maxValue,
      maxValue: 0,
      numOfLayer: 1,
      type: "Width",
      value: 1,
    },
  ];
}

function delWasherRule() {
  const end = washerRuleData.value.length - 1;
  washerRuleData.value = washerRuleData.value.slice(0, end);
}

function handleDataChange(type: string, num: number) {
  if (type === "Varying") {
    data.value = new Array(num)
      .fill({ type: "Width", value: 1 })
      .map((item, index) => ({ ...item, id: `${index}` }));
  } else {
    data.value = [{ id: "0", type: "Width", value: 1 }];
  }
  tableWasher.value?.refresh();
}

function onChangeSelector(val: number) {
  coreStore.setEngineState(val);
}

const getParams = () => {
  const params: WasherCreateOptions = {
    type: formWasher.type,
    metaData: {},
    boundaryLayer: formWasher.boundaryLayer ? 1 : 0,
  };
  if (formWasher.type === "Rule") {
    params["metaData"]["maxValues"] = washerRuleData.value.map(
      (row) => row["maxValue"]
    );
    params["metaData"]["minValues"] = washerRuleData.value.map(
      (row) => row["minValue"]
    );
    params["metaData"]["numOfLayers"] = washerRuleData.value.map(
      (row) => row["numOfLayer"]
    );
    params["metaData"]["types"] = washerRuleData.value.map(
      (row) => row["type"]
    );
    params["metaData"]["values"] = washerRuleData.value.map(
      (row) => row["value"]
    );
  } else {
    params["numOfLayers"] = formWasher.numOfLayers;
    params["metaData"]["types"] = data.value.map((row) => row["type"]);
    params["metaData"]["values"] = data.value.map((row) => row["value"]);
  }
  return params
}

function onSetWashers() {
  const params = getParams()
  _global.Engine.washer
    .select()
    .then((res) => {
      if (res) {
        _global.Engine.washer.create(params).then((res) => {
          console.log("washer create res", res);
          Notice.success("垫圈网格设置成功");
        });
      } else {
        Notice.error("面和边选择失败");
      }
    })
    .catch((err) => {
      Notice.error(`未选择任何边或面`);
    });
}

function onSearch() {
  const params = {
    ...formSearch,
  };
  _global.Engine.washer
    .select()
    .then((res) => {
      if (res) {
        _global.Engine.washer.findpinhole(params).then((res) => {
          console.log("washer findpinhole res", res);
          const { entityFaceIndex, entityId, entityType, partId } = res;
          entityId.forEach((edgeId: number, i: number) => {
            _global.Engine.setSelectEdgeByEdgeId(edgeId, 0, partId[i]);
          })
          Notice.success("搜索成功");
        });
      } else {
        Notice.error("面和边选择失败");
      }
    })
    .catch((err) => {
      Notice.error(`未选择任何边或面`);
    });
}

function onSetHoles() {
  const params = {
    symbolType: ruleSymbolType.value,
    curveData: {
      maxValues: ruleData.value.map((row) => row["maxValue"]),
      minValues: ruleData.value.map((row) => row["minValue"]),
      types: ruleData.value.map((row) => row["type"]),
      values: ruleData.value.map((row) => row["value"]),
    },
  };
  _global.Engine.washer
    .select()
    .then((res) => {
      if (res) {
        _global.Engine.washer.setHole(params).then((res) => {
          console.log("washer setHole res", res);
          Notice.success("规则设置成功");
        });
      } else {
        Notice.error("面和边选择失败");
      }
    })
    .catch((err) => {
      Notice.error(`未选择任何边或面`);
    });
}

function handleClear(mode: number) {
  _global.Engine.washer.clear()
}

function onClear() {
  const params = getParams()
  _global.Engine.washer.clear({...params, height1st: 1})
}

watch(WasherModalVueActive, (show) => {
  if (show) {
    _global.Engine.washer.enter()
    coreStore.setEngineState(activeSelector.value);
  } else {
    _global.Engine.washer.leave();
    coreStore.setEngineState(STATUS_CODE.NORMAL);
  }
});
</script>

<style scoped lang="less">
.footer,
.btn-wrap {
  display: flex;
  justify-content: flex-end;
}
.footer {
  padding-top: 16px;
  border-top: solid 1px var(--vxp-modal-d-color);
}
.title {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 16px;
  margin-bottom: 16px;

  .title_color {
    width: 4px;
    height: 12px;
    background: #339af0;
    margin-right: 8px;
  }
  .title_content {
    opacity: 1;
    font-family: PingFang SC;
    font-size: 14px;
    font-weight: 600;
    line-height: 22px;
    letter-spacing: 0em;
    font-variation-settings: "opsz" auto;
    /* content/主要一级primary */
    /* 样式描述：--vxp-content-color-primary */
    color: #212529;
  }
}
.chose-box {
  padding-left: 6%;
  margin-bottom: 10px;
}
.radio_box {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}
.radio_item {
  display: inline-block;
  width: 220px;
}
.selector-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}
.selector-button {
  display: inline-block;
  height: 22px;
  width: 160px;
  padding: 0 16px;
  border: 1px solid #ccc;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  background-color: #fff;
  cursor: pointer;
  outline: none;
}

.selector-button.active {
  background-color: #e6f7a7;
  /* flex-grow: 1; */
  font-weight: normal;
}
.icon-button {
  width: 32px;
  height: 22px;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  border: 1px solid #ccc;
  border-left: none;
  cursor: pointer;
  background-color: #fff;
}
.icon-button:hover {
  background-color: var(--vxp-color-warning-opacity-7);
}
.imgStyle {
  height: 100%;
}
</style>
